package run.bottle.provider;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception{
        channels.add(ctx.channel());//加入ChannelGroup
        System.out.println(ctx.channel().id()+" 加入聊天室,"+"在线人数: "+channels.size());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext context){
        System.out.println(context.channel().id()+" 离开了聊天室,"+"在线人数: "+channels.size());
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //打印消息然后群发
        System.out.println(msg.toString());
        for (Channel channel:channels){
            channel.writeAndFlush(msg.toString());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(ctx.channel().id()+" 发生异常,"+"在线认数: "+channels.size());
        ctx.close();
    }
}
